<?php


/**
 * @package EDO
 * @subpackage Collections
 *
 */
abstract class Lead_EDO_Collection_Abstract extends Lead_Event_Observable_Abstract implements Iterator, Countable
{
 
   	protected $_length = 0;
	protected $_currIndex = 0;
	protected $_items = array();
    
	protected $_handler;
	
	protected $_object;
	
	
		
	public function __construct(Lead_EDO_Handler_Interface $edo)
	{
		$this->_handler = $edo;
		$this->_items = array();
		$this->_length = 0;
	}	
	
	
	/**
	 * Handler
	 *
	 * @return EDOHandler
	 */
	public function getHandler()
	{
	    return $this->_handler;
	}
	
	
	public function getClone($items)
	{
	    return $this->_handler->collection($this->getObject(), $items);
	}
	
	
	
	public function setObject($object)
	{
		if($object instanceof Lead_EDO_Item_Abstract)
	        $this->_object = $object->getClass();
	    elseif(is_string($object))
	        $this->_object = $object;
	    else
	        throw new Lead_EDO_Exception('Wrongful object type for collection');
	}
	
	
    public function setItems($items)
    {
        $this->_items = array();
        if(is_array($items))
        {
            foreach($items as &$item)
            {
                $this->addItem($item);
            }   		
        }
        $this->_length = sizeof($this->_items);
    }
        		
	
	function rewind() {
		$this->_currIndex = 0;
	}
	
	function valid()
	{
		return ($this->_currIndex < $this->_length);
	}
	
	function key() {
		return $this->_currIndex;
	}
	
	function current() {
		if($this->valid())
		{
		    return $this->getItem($this->_currIndex);
		}
		return false;
	}
	
	function next() {
		$this->_currIndex++;
	}
	
	
	public function addItem($res)
	{
		if(!is_array($res))
		    $res = array($res);
	    
		foreach($res as $id) {
		    array_push($this->_items, $id);
		}
		    
		$this->_length = sizeof($this->_items);	
	}
	
	
	public function getItem($itemid)
	{
	    return $this->getHandler()->fetch($this->_items[$itemid], $this->_object);
	}
	
	
	public function getKeys()
	{
		return $this->_items;
	}

	

	/**
	 * Implements Countable from SPL
	 *
	 * @return integer Size of the collection
	 */
	public function count()
	{
		return $this->_length;
	}
	
	
	public function getObject()
	{
		return $this->_object;
	}
	
	
	public function isFirst()
	{
	    return (bool) ($this->_currIndex == 0);
	}
	
	public function isLast()
	{
	    return (bool) ($this->_currIndex == $this->count() -1);
	}
	
	
	public function page($pageSize, $startPage)
	{
        Zend_Loader::loadClass('Lead_EDO_Collection_Pager');
        $pager = new Lead_Edo_Collection_Pager($this, $pageSize, $startPage);
        return $pager;        
	}
	
	
	
	public function __toString()
	{
	    $output = '';
	    foreach($this as $obj) {
	        $output .= $obj->__toString() . "\n";
	    }
	    
	    return $output;
	}
	
	
}




?>
